package com.mairuide.bill.billdetail;

import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.base.PageSupport;
import com.mairuide.bill.DealFlow;
import com.mairuide.bill.DealFlowService;
import com.mairuide.bill.DealFlowVo;
import com.mairuide.bill.utils.DateUtils;
import com.mairuide.bill.utils.ExcelUtil;
import com.mairuide.bill.utils.ExcelUtils;
import com.mairuide.datalog.ActionType;
import com.mairuide.datalog.DataOperationLogService;
import com.mairuide.datalog.ModuleFlag;
import com.mairuide.datalog.SystemFlag;

/**
 * 交易账单详情
 * @author songRT
 */
@Controller
@RequestMapping("/bill/tj")
public class BillDetailController extends BaseController {
	@Resource
	private DealFlowService dealFlowService;
    @Resource
    private DataOperationLogService dataOperationLogService;

	@ModuleCode(pValue = "bill", value = "billdetail")
	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public Object billdetail(ModelMap model, PageSupport pagesupport) {
		model.addAttribute("menu", "billdetail");
		return "/bill/billDetail";
	}
	
	@ResponseBody
	@RequestMapping(value = "/billDetailList")
	public Object billDetail(DealFlowVo dealFlow) {
		return dealFlowService.findBillByPage(dealFlow);
	}
	
	@RequestMapping(value = "/detailD3Init", method = RequestMethod.GET)
	public Object detailD3Init(ModelMap model, PageSupport pagesupport) {
		return "/bill/detailD3Init";
	}
	
	
	@RequestMapping(value = "/detailD3Dialog", method = RequestMethod.GET)
	public Object detailD3Dilag(ModelMap model, PageSupport pagesupport) {
		return "/bill/detailD3Dialog";
	}
	
	@ResponseBody
	@RequestMapping(value = "/detailD3")
	public Object detailD3(DealFlowVo dealFlow) {
		return dealFlowService.detailD3(dealFlow);
	}
	
	@ResponseBody
	@RequestMapping(value = "/detailD3DialogData")
	public Object detailD3DialogData(DealFlowVo dealFlow) {
		return dealFlowService.detailD3DialogData(dealFlow);
	}

    /**
     * 账单导出
     * @throws Exception
     */
    @RequestMapping(value = "/detail/export",method = RequestMethod.POST)
    @ResponseBody
    public void exportFile(String sort,String order,HttpServletResponse response, DealFlowVo dealFlow) throws Exception {

        XSSFWorkbook workbook1 = new XSSFWorkbook();
        SXSSFWorkbook wb = new SXSSFWorkbook(workbook1, 100);
        //创建HSSFWorkbook对象(excel的文档对象)
//        HSSFWorkbook wb = new HSSFWorkbook();
        //建立新的sheet对象（excel的表单）
        Sheet sheet1=wb.createSheet("一级账号交易详情");
        PageRequest pageRequest = new PageRequest(0,Integer.MAX_VALUE);
        Page<DealFlow> firstPage = dealFlowService.findBillByPage(dealFlow, pageRequest,sort,order);
        List<DealFlow> firstList = firstPage.getContent();
        writeIn(sheet1,firstList);
        if (dealFlow.getSign()==0||dealFlow.getSign()==1){
            Sheet sheet2=wb.createSheet("二级账号交易详情");
            Sheet sheet3=wb.createSheet("三级账号交易详情");
            List<String> second = firstList.stream().map(DealFlow::getAccountRivalCard).collect(Collectors.toList());
            List<DealFlow> secondPage = dealFlowService.secondBill(second,dealFlow);
            List<String> third = secondPage.stream().map(DealFlow::getAccountRivalCard).collect(Collectors.toList());
            List<DealFlow> thirdPage = dealFlowService.thirdBill(third,dealFlow);
            writeIn(sheet2,secondPage);
            writeIn(sheet3,thirdPage);
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "账单明细" + dateFormat.format(new Date());
        //输出Excel文件
        OutputStream output=response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename="+ ExcelUtils.toUtf8String(fileName+".xlsx"));
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
        //插入导出日志
        dataOperationLogService.save(null, super.getLoginUser(), new DealFlow(), new DealFlow(), SystemFlag.ZD, ModuleFlag.BILLDETAIL, ActionType.EXPORT);


    }
    private void writeIn (Sheet sheet ,List<DealFlow> list){
        //在sheet里创建第一行
        Row row2=sheet.createRow(0);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("交易主体");
        row2.createCell(1).setCellValue("交易主体卡号");
        row2.createCell(2).setCellValue("交易对手");
        row2.createCell(3).setCellValue("交易对手卡号");
        row2.createCell(4).setCellValue("交易总金额");
        row2.createCell(5).setCellValue("交易总次数");
        row2.createCell(6).setCellValue("最早交易时间");
        row2.createCell(7).setCellValue("最晚交易时间");
        String addStr = "A0:"+ ExcelUtil.letter[7]+"0";
        CellRangeAddress addr = CellRangeAddress.valueOf(addStr);
        sheet.setAutoFilter(addr);
        if (list!=null && list.size()>0) {
            for (int i = 0; i < list.size(); i++) {
                DealFlow df = list.get(i);
                Row row3 = sheet.createRow(i + 1);
                row3.createCell(0).setCellValue(df.getAccountBody());
                row3.createCell(1).setCellValue(df.getAccountBodyCard());
                row3.createCell(2).setCellValue(df.getAccountRival());
                row3.createCell(3).setCellValue(df.getAccountRivalCard());//交易对手卡号
                row3.createCell(4).setCellValue(df.getAccountMoney()==null?"":df.getAccountMoney().toString());//交易总金额
                row3.createCell(5).setCellValue(df.getCreateId());//交易总次数
                row3.createCell(6).setCellValue(df.getTradeDate()==null?"": DateUtils.getDateString(df.getTradeDate()));//最早交易日期
                row3.createCell(7).setCellValue(df.getCreateTime()==null?"":DateUtils.getDateString(df.getCreateTime()));//最晚交易日期

            }
        }
    }
}
